package org.csu.mybigpro.controller;

import org.csu.mybigpro.common.CommonResponse;
import org.csu.mybigpro.service.VirtualStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/api/simulations")
public class SimulationController {

    @Autowired
    private VirtualStudentService virtualStudentService;

    // 【修改点1】使用一个Map来存储每个房间的课堂主题
    private final Map<String, String> roomContexts = new ConcurrentHashMap<>();

    @PostMapping("/start")
    public CommonResponse<?> start(@RequestBody Map<String, String> payload) {
        String roomName = payload.get("roomName");
        String lessonContext = payload.get("lessonContext");

        if (roomName != null && lessonContext != null) {
            // 【修改点2】当模拟开始时，将课堂主题存入Map
            roomContexts.put(roomName, lessonContext);
            System.out.println("收到前端开启模拟的信号，房间: " + roomName + ", 主题: " + lessonContext);
            return CommonResponse.createForSuccessMessage("虚拟学生模拟已在前端启动");
        }
        return CommonResponse.createForError("房间名或课堂主题不能为空");
    }

    @PostMapping("/stop")
    public CommonResponse<?> stop(@RequestBody Map<String, String> payload) {
        // 停止时，可以从Map中移除该房间的上下文
        String roomName = payload.get("roomName");
        if (roomName != null) {
            roomContexts.remove(roomName);
        }
        System.out.println("收到前端停止模拟的信号。");
        return CommonResponse.createForSuccessMessage("虚拟学生模拟已在前端停止");
    }

    @PostMapping("/teacher-speech")
    public CommonResponse<?> receiveTeacherSpeech(@RequestBody Map<String, String> payload) {
        String roomName = payload.get("roomName");
        String transcript = payload.get("transcript");

        // 【修改点3】从Map中获取当前房间对应的课堂主题，如果找不到则使用默认值
        String lessonContext = roomContexts.getOrDefault(roomName, "默认课堂");

        virtualStudentService.processTeacherSpeech(roomName, lessonContext, transcript);

        return CommonResponse.createForSuccess();
    }
}